package org.example.service;

import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.java.Log;
import org.example.bean.*;
import org.example.configs.OssConfig;
import org.example.dao.AddressMapper;
import org.example.dao.CategoryMapper;
import org.example.dao.OrdersMapper;
import org.example.dao.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@AllArgsConstructor
@Log
public class OrdersServiceImpl implements OrdersService {
    private final MessageService messageService;

    private final OrdersMapper ordersMapper;
    private final UserMapper userMapper;
    private final AddressMapper addressMapper;
    private final OssConfig ossConfig;
    private final OSS ossClient;

    @Override
    @Transactional
    public Orders addOrder(Orders orders) {
        //先判断当前用户是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUser_id, orders.getUser_id());
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        //判断地址是否存在
        LambdaQueryWrapper<Address> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Address::getAddress_id, orders.getAddress_id());
        Address address = addressMapper.selectOne(wrapper1);
        if (address == null) {
            throw new RuntimeException("地址不存在");
        }
        ordersMapper.insert(orders);
        return orders;
    }

    @Override
    public List<Orders> findUnfinishedOrder(Integer order_status1) {
        return ordersMapper.selectByOrderStatusWithProduct(order_status1);
    }

    //根据订单id修改订单状态
    @Override
    @Transactional
    public boolean updateOrderStatus(Integer orderId, Integer orderStatus) {
        Orders orders = ordersMapper.selectById(orderId);
        if (orders == null) {
            throw new RuntimeException("订单不存在");
        }
        orders.setOrder_status(orderStatus);
        return ordersMapper.updateById(orders) > 0;
    }

    @Override
    @Transactional
    public List<Orders> findOrderById(Integer order_id) {
        return ordersMapper.selectByOrderIdWithProduct(order_id);
    }

    //    处理消息
    @Override
    @Transactional
    public void order(Integer id) {
        //一系列操作，包含各种服务调用，处理各种业务
        System.out.println("订单处理开始");
        //短信消息处理
        messageService.sendMessage(id.toString());
        System.out.println("订单处理结束");
        System.out.println();
    }
}
